<?php
namespace app\admin\controller;
use app\model\Attach;
use app\model\AttachType;
use app\util\ReturnCode;
use tegic\qiniu\Qiniu;
use think\Db;

class Upload extends Base
{
    /**
     * 获取文件列表
     * @return false|string
     */
    public function getAttach(){
        $where = [
            'type' => $this->request->post('type',0)
        ];
        $page = $this->request->post('page',1);
        $size = $this->request->post('size',32);
        $data = (new Attach())->getList($where, $page , $size);
        return $this->buildSuccess($data);
    }

    /**
     * 批量移动图片到其他分类
     * @return false|string
     */
    public function moveAttachToType(){
        $typeId = $this->request->post('typeId',0);
        $attachList = $this->request->post('attachList');
        Attach::update(['type'=>$typeId],['id'=>$attachList]);
        return $this->buildSuccess([]);
    }

    /**
     * 删除文件,判断save_type 1.删除本地文件,2.删除七牛文件
     * @return false|string
     */
    public function delAttach(){
        $id = $this->request->post('id');
        if(!$id)
            return $this->buildFailed(ReturnCode::EMPTY_PARAMS, '参数错误');
        Db::startTrans();
        try{
            $paths = Attach::select($id)->toArray();
            Db::name( 'attach')->delete($id);
            Db::commit();
            $qiniu = new Qiniu();
            foreach ($paths as $key => $value){
                if($value['save_type'] === Attach::LOCALTYPE){
                    if(file_exists($value['path'])) unlink($value['path']);
                }else{
                    $qiniu->delete(config('app.qiniu.bucket'),$value['qn_key']);
                }
            }
            return $this->buildSuccess([]);
        } catch (\Exception $e) {
            Db::rollback();
            $this->buildFailed($e->getCode(),$e->getMessage());
        }
    }

    /**
     * 获取分类列表
     * @return false|string
     */
    public function getType(){
        try {
            $list = AttachType::select()->toArray();
            return $this->buildSuccess($list);
        } catch (\Exception $e) {
            return $this->buildFailed($e->getCode(),$e->getMessage());
        }
    }

    /**
     * 新增分类
     * @return false|string
     */
    public function saveType(){
        $data = $this->request->post();
        if($data['id'])
            $res = AttachType::update($data);
        else
            $res = AttachType::create(['name'=>$data['name']]);
        return $this->buildSuccess($res);
    }

    /**
     * 删除分类,批量设置此分类下的图片
     * @return false|string
     */
    public function delType(){
        $id = $this->request->post('id', '');
        if(!$id)
            return $this->buildFailed(ReturnCode::EMPTY_PARAMS,'参数错误');
        Db::startTrans();
        try {
            Db::name( 'attach_type')->delete($id);
            Db::name( 'attach')->where(['type'=>$id])->update(['type'=>0]);
            Db::commit();
            return $this->buildSuccess([]);
        } catch (\Exception $e) {
            Db::rollback();
            return $this->buildFailed($e->getCode(),$e->getMessage());
        }
    }

    /**
     * 上传到本地服务器
     * @return false|string
     */
    public function doUpload(){
        if($this->request->post('Authorization')){
            $typeId = $this->request->post('typeId',0);
            $file = $this->request->file('file');
            $savePath = './uploads';
            if (!is_dir($savePath))
                mkdir($savePath, 0755, true);

            $info = $file->validate(['size'=>2097152,'ext'=>'jpg,jpeg,png,gif'])->move($savePath);
            if($info){
                $attach = Attach::create([
                    'type' => $typeId,
                    'name' => $info->getFilename(),
                    'save_type' => Attach::LOCALTYPE,
                    'ext' => $info->getExtension(),
                    'size' => $info->getSize(),
                    'path' => $savePath.'/'.str_replace('\\','/',$info->getSaveName()),
                    'create_time' => time()
                ]);
                $path = $this->request->domain().ltrim($attach['path'],'.');
                return $this->buildSuccess($path);
            }else{
                return $this->buildFailed(ReturnCode::ADD_FAILED,$file->getError());
            }
        }
    }

    /**
     * 保存七牛上传后的key
     * @return false|string
     */
    public function qiniuUpload(){
        $key = $this->request->post('key','');
        $type = $this->request->post('type',0);
        if(!$key)
            return $this->buildFailed(ReturnCode::EMPTY_PARAMS, '参数错误');

        $attach = Attach::create([
            'type' => $type,
            'name' => $key,
            'save_type' => Attach::QINIUTYPE,
            'qn_key' => $key,
            'path' => config('app.qiniu.domain').$key,
            'create_time' => time()
        ]);
        return $this->buildSuccess($attach['path']);
    }

    /**
     * 判断是否开启七牛，获取七牛token
     * @return false|string
     */
    public function getQiniuToken(){
        if(config('app.qiniu.is_qiniu')){
            try{
                $token = (new Qiniu())->getToken();
                $return = [
                    'token' => $token,
                    'isQiNiu' => 1
                ];
                return $this->buildSuccess($return);
            }catch (\Exception $e){
                return $this->buildFailed($e->getCode(),$e->getMessage());
            }
        }else{
            return $this->buildSuccess(['isQiNiu'=>0]);
        }
    }
}
